/*
 * IlluminateDisplay.cpp
 *
 *  Created on: Feb 6, 2011
 *      Author: kmueller
 */

#include "IlluminateDisplay.h"

#include "MainWindow.h"

#include "../logic/Main.h"
#include "../logic/Settings.h"
#include "../logic/PositioningSystem.h"

#include <QtCore>

IlluminateDisplay::IlluminateDisplay(MainWindow* parent) :
	QTimer(static_cast<QObject*> (parent)) {

#ifdef Q_WS_MAEMO_5
	setInterval(5000);

	ossoContext = osso_initialize(Main::APPLICATION_NAME(), "1.0", FALSE, NULL);

	connect(this, SIGNAL(timeout()), this, SLOT(illuminate()));

	updateStatus();
#endif
	AbstractSetting* s = Main::getInstance().getSettings().getUnblank();
	connect(s, SIGNAL(settingChanged(AbstractSetting *)), this, SLOT(updateStatus()));

	connect(&Main::getInstance().getPositioningSystem(), SIGNAL(startedMoving()), this, SLOT(updateStatus()));
	connect(&Main::getInstance().getPositioningSystem(), SIGNAL(stoppedMoving()), this, SLOT(updateStatus()));
}

IlluminateDisplay::~IlluminateDisplay() {
	//#ifdef Q_WS_HILDON
#ifdef Q_WS_MAEMO_5
	if (ossoContext != NULL) {
		osso_deinitialize(ossoContext);
		ossoContext = NULL;
	}
#endif
}

void IlluminateDisplay::updateStatus() {
	AbstractSetting* s = Main::getInstance().getSettings().getUnblank();
	PositioningSystem* p = &Main::getInstance().getPositioningSystem();

	stop();

	switch (s->getCurrent()) {
	case Unblank::CONNECTED: {
		if (p->isEnabled() && p->getLastPosition().isValid()) {
			start();
			return;
		}
	}
		break;
	case Unblank::MOVING: {
		if (Main::getInstance().isMoving()) {
			start();
			return;
		}
	}
		break;
	case Unblank::MOVING_FULL: {
		if (Main::getInstance().isMoving()
				&& dynamic_cast<MainWindow*> (parent())->isFullScreen()) {
			start();
			return;
		}
	}
		break;
	case Unblank::NAVIGATION: {
		if (Main::getInstance().isNavigating()
				&& dynamic_cast<MainWindow*> (parent())->isFullScreen()) {
			start();
			return;
		}
	}
		break;
	case Unblank::NAVIGATION_FULL: {
		if (Main::getInstance().isNavigating()
				&& dynamic_cast<MainWindow*> (parent())->isFullScreen()) {
			start();
			return;
		}
	}
		break;
	case Unblank::WAYPOINT:
		// TODO: needs implementation
		break;
	case Unblank::NEVER: {
		stop();
		return;
	}
		break;
	}
}

void IlluminateDisplay::illuminate() {
	//#ifdef Q_WS_HILDON
#ifdef Q_WS_MAEMO_5
//	qDebug() << "illuminate Display";
	if (osso_display_state_on(ossoContext) != OSSO_OK) {
		qDebug() << QString("osso_display_state_on failed.");
	}
#endif
}
